﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Uber.Storage;
using System.Data;
using Uber.HabboHotel.GameClients;

namespace Uber.HabboHotel.Misc
{
    public class LotteryManager
    {
        int lastStamp = 0;
        Random random;

        public LotteryManager(int seed = -1)
        {
            lastStamp = Convert.ToInt32((DateTime.Now).ToString("HHmmss"));
            if (seed != -1) random = new Random(seed);
            else random = new Random();
        }

        public void Update(bool force = false)
        {
            try
            {
                int currStamp = Convert.ToInt32((DateTime.Now).ToString("HHmmss"));
                int offset = (currStamp < lastStamp) ? 240000 : 0;
                if (currStamp - lastStamp + offset >= 20000 || force)
                {
                    lastStamp = currStamp;
                    int[] nums = this.MakeNumbers();
                    using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
                    {
                        string numbers = "";
                        for (int i = 0; i < 7; i++) { numbers += " " + nums[i]; }
                        numbers = numbers.Substring(1);
                        dbClient.ExecuteQuery("INSERT INTO lottery (timestamp, numbers) VALUES ('" + DateTime.Now + "', '" + numbers + "')");
                    }
                    this.GiveMoney(nums);
                }
            }
            catch(Exception e) 
            {
                UberEnvironment.GetLogging().WriteLine("Lottery Error: " + e.Message);
            }
        }

        public int[] MakeNumbers()
        {
            bool notdone = true; ;
            int[] numbers = new int[7] { -1, -1, -1, -1, -1, -1, -1 };
            int currIndex = 0;
            while (notdone)
            {
                int newNum = random.Next(0, 21);
                bool flag = false;
                for (int i = 0; i < numbers.Length; i++)
                {
                    if (newNum == numbers[i]) flag = true;
                }
                if (!flag && currIndex < 7) { numbers[currIndex] = newNum; currIndex++; }
                if (currIndex > 6) { notdone = false; }
            }
            UberEnvironment.GetLogging().WriteLine("Making numbers");
            return numbers;
        }

        public void GiveMoney(int[] nums)
        {
            using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
            {

                DataTable entries = dbClient.ReadDataTable("SELECT * FROM lottery_entries");
                try
                {
                    foreach (DataRow user in entries.Rows)
                    {
                        bool[] hasNumber = new bool[7];
                        bool[] inOrder = new bool[7];
                        string number_plainttext = Convert.ToString(user["numbers"]);
                        string[] numbers = number_plainttext.Split(' ');
                        for (int i = 0; i < numbers.Length; i++)
                        {
                            for (int n = 0; n < nums.Length; n++)
                            {
                                Console.WriteLine("-" + numbers[i] + "-");
                                if (Convert.ToInt32(numbers[i]) == nums[n])
                                {
                                    hasNumber[n] = true;
                                    inOrder[i] = i == n;
                                }
                            }
                        }

                        int prizeCount = 0;
                        int orderCount = 0;
                        for (int i = 0; i < 7; i++)
                        {
                            if (hasNumber[i] == true) prizeCount++;
                            if (inOrder[i] == true) orderCount++;
                        }

                        GameClient g = UberEnvironment.GetGame().GetClientManager().GetClientByHabbo(UberEnvironment.GetGame().GetClientManager().GetIdByName(user["username"].ToString()));
                        int won = 0;
                        //bool online = true;
                        bool online = Convert.ToBoolean(dbClient.ReadDataRow("SELECT * FROM users WHERE username='" + g.GetHabbo().Username + "'")["online"]);
                        if (online && orderCount == 7) { g.GetHabbo().Credits += 10000; g.GetHabbo().UpdateCreditsBalance(true); won = 10000; }
                        else
                        {
                            if (online && prizeCount == 7) { g.GetHabbo().Credits += 6000; g.GetHabbo().UpdateCreditsBalance(true); won = 6000; }
                            if (online && prizeCount == 6) { g.GetHabbo().Credits += 3000; g.GetHabbo().UpdateCreditsBalance(true); won = 3000; }
                            if (online && prizeCount == 5) { g.GetHabbo().Credits += 2000; g.GetHabbo().UpdateCreditsBalance(true); won = 2000; }
                            if (online && prizeCount == 4) { g.GetHabbo().Credits += 1500; g.GetHabbo().UpdateCreditsBalance(true); won = 1500; }
                            if (online && prizeCount == 3) { g.GetHabbo().Credits += 1000; g.GetHabbo().UpdateCreditsBalance(true); won = 1000; }
                        }
                        try
                        {
                            if (online && won > 0) { g.SendNotif("Lottery was drawn. You won " + won + " credits!"); }
                            else if (online) { g.SendNotif("Lottery was drawn. You won nothing. Sorry!"); }
                        }
                        catch (Exception e)
                        {
                            UberEnvironment.GetLogging().WriteLine("Lottery Error: " + e.Message + ":" + e.Source);
                        }
                    }
                }
                catch (Exception e)
                {
                    UberEnvironment.GetLogging().WriteLine("Whatever Error: " + e.Message +":" + e.StackTrace);
                }

                dbClient.ExecuteQuery("TRUNCATE TABLE lottery_entries");
            }
        }

        public static void AddTicket(String username, string numbers)
        {
            using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
            {
                numbers = numbers.Substring(1);
                bool update = false;
                try
                {
                    DataRow row = dbClient.ReadDataRow("SELECT * FROM lottery_entries WHERE username='" + username + "'");
                    if (row != null)
                    {
                        update = true;
                    }
                }
                catch (RowNotInTableException e)
                {
                    update = false;
                }
                if (update)
                {
                    dbClient.ExecuteQuery("UPDATE lottery_entries SET numbers='" + numbers + "' WHERE username='" + username + "'");
                }
                else
                {
                    dbClient.ExecuteQuery("INSERT INTO lottery_entries (username, numbers) VALUES ('" + username + "', '" + numbers + "')");
                }
            }
        }
    }
}
